//
//  QTTools.m
//  TSQTProduct
//
//  Created by Tsou on 2017/5/15.
//  Copyright © 2017年 周彬. All rights reserved.
//

#import "QTTools.h"
#import <CommonCrypto/CommonDigest.h>
#import "Encipherment.h"
@implementation QTTools

+(instancetype)shareTool{
    static dispatch_once_t onceToken;
    static QTTools *tools = nil;
    dispatch_once(&onceToken, ^{
        tools = [[QTTools alloc]init];
    });
    return tools;
}
//
+ (NSString*)tool_netStatus{
    // 状态栏是由当前app控制的，首先获取当前app
    //如果状态栏被隐藏了要先让它显示出来，然后在之后隐藏
    UIApplication *app = [UIApplication sharedApplication];
    app.statusBarHidden = NO;
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    
    NSString *stateString = @"wifi";
    
    switch (type) {
        case 0:
            stateString = @"notReachable";
            break;
            
        case 1:
            stateString = @"2G";
            break;
            
        case 2:
            stateString = @"3G";
            break;
            
        case 3:
            stateString = @"4G";
            break;
            
        case 4:
            stateString = @"LTE";
            break;
            
        case 5:
            stateString = @"wifi";
            break;
            
        default:
            stateString = @"无法检测网络环境";
            break;
    }

    [[UIApplication sharedApplication] setStatusBarHidden:[self fc_isStatusBarHidden]];
    
    return stateString;
}
//判断状态栏是否被隐藏
+ (BOOL)fc_isStatusBarHidden{
    
    UIApplication* app = [UIApplication sharedApplication];
    
    id statusBar = [app valueForKeyPath:@"statusBar"];
    
    if (statusBar) {
        return NO;
    }
    return YES;
    
}
//
//NSString 是否是空 yes为空
+ (BOOL)isBlankString:(NSString *)string{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}
+(NSString *)tool_object:(id)object placeHolder:(NSString*)placeholder{
    if ([object isEqual: [NSNull null]] || object == nil || object == NULL ){
        //
        return placeholder;
        
    }else if ([object isKindOfClass:[NSNumber class]]){
        //
        return [object stringValue];
        
    }else if ([object isKindOfClass:[NSString class]]){
        //
        NSString* tmp = (NSString*)object;
        if ([tmp isEqualToString:@""]) {
            //
            return placeholder;
        }
        if ([[tmp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
            //
            return placeholder;
        }
        if ([tmp isEqualToString:@"null"]) {
            //
            return placeholder;
        }
    }else{
        
        NSString* tmps = [NSString stringWithFormat:@"%@",object];
        
        return tmps;
    }
    
    return object;
}
//
+(NSDictionary *)tool_objectDic:(id)object{
    if ([object isKindOfClass:[NSDictionary class]]) {
        return object;
    }
    return @{};
}
//
+(NSArray *)tool_objectArray:(id)object{
    if ([object isKindOfClass:[NSArray class]]) {
        return object;
    }
    return @[];
}
/**
 * 颜色保存
 */
+(void)tool_saveR:(NSString *)red G:(NSString *)green B:(NSString *)blue{
//    [kQTUserDefaults setObject:red forKey:kAppRed];
//    [kQTUserDefaults setObject:green forKey:kAppGreen];
//    [kQTUserDefaults setObject:blue forKey:kAppBlue];
//    [kQTUserDefaults synchronize];
}
/**
 * 获取颜色
 */
+(UIColor *)tool_getColor{
//    themeColor
    UIColor *appColor = [UIColor colorWithRed:243/255.0 green:71/255.0  blue:71/255.0  alpha:1];
    return appColor;
}
//
+(NSString *)tool_objectMoney:(id)object{
    //
    if ([object isKindOfClass:[NSNumber class]]) {
        //
        NSString* tmp = [NSString stringWithFormat:@"%0.2f",[object doubleValue]];
        return tmp;
    }else if ([object isKindOfClass:[NSString class]]){
        NSString* tmp = (NSString*)object;
        double dd = [tmp doubleValue];
        tmp = [NSString stringWithFormat:@"%0.2f",dd];
        return tmp;
    }
    return @"暂无";
}

+(BOOL)tool_objectMoneyAll:(NSString *)object{
    if (object.length > 0) {
        NSString *stringRegex = @"(\\+|\\-)?(([0]|(0[.]\\d{0,2}))|([1-9]\\d{0,4}(([.]\\d{0,2})?)))?";
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringRegex];
        BOOL flag = [phoneTest evaluateWithObject:object];
        if (!flag) {
            return NO;
        }
    }
    
    return YES;
}
//
+(BOOL)tool_objectIDCard:(NSString *)object{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:object];
    return isMatch;
}
//
+(void)tool_shoIndicatorOnView:(UIView *)viewsuper{
    [self tool_hiddenIndicatorOnView:viewsuper];
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithFrame:viewsuper.bounds];
    activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    activity.tag =  99;
    [viewsuper addSubview:activity];
    [activity startAnimating];
    
}
+ (void)tool_hiddenIndicatorOnView:(UIView *)viewsuper{
    UIActivityIndicatorView* activityView = (UIActivityIndicatorView*)[viewsuper viewWithTag:99];
    [activityView stopAnimating];
    [activityView removeFromSuperview];
}
//
+(BOOL)tool_objectPhoneNumber:(NSString *)object{
    //返回YES表示可用的手机号码
    if (object.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:object] == YES)
        || ([regextestcm evaluateWithObject:object] == YES)
        || ([regextestct evaluateWithObject:object] == YES)
        || ([regextestcu evaluateWithObject:object] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
//
+(CGFloat)tool_getHeightWithSize:(CGSize)size currWidth:(CGFloat)currWidth{
    CGFloat w = size.width;
    CGFloat h = size.height;
    return currWidth*h/w;
}
//
+(NSString *)tool_MD5:(NSString *)object{
    const char *original_str = [object UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}
//
+(UIView *)tool_addLineWithFrame:(CGRect)frame superView:(UIView *)superView{
    UIView* line = [[UIView alloc] initWithFrame:frame];
    line.backgroundColor = LineCOLOR;
    [superView addSubview:line];
    return line;
}
//
+ (BOOL)tool_objectLogin{
    //判断有无登录凭证
    NSString* userticket = [self tool_getUserCookie];
    if (!userticket) {
        //
        return NO;
    }
    return YES;
}
//
+(NSString *)tool_getUserCookie{
    return [kQTUserDefaults objectForKey:kMark_userCookie];
}
+(void)remove_userCookie{
    [kQTUserDefaults removeObjectForKey:kMark_userCookie];
    [kQTUserDefaults synchronize];
}
//
+(BOOL)tool_objectMail:(NSString *)object{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:object];
}

//
+(BOOL)tool_objectPassword:(NSString *)object{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:object];
    return isMatch;
}
//
+(BOOL)tool_objectBankNumber:(NSString *)object{
    NSString *regex2 =@"^\\d{16,19}$|^\\d{6}[- ]\\d{10,13}$|^\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4,7}$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:object];
}
//
+ (CGSize)tool_getStringSizeWith:(NSString*)_mystr boundingRectWithSize:(CGSize)_boundSize font:(UIFont*)font{
    _mystr = [self tool_object:_mystr placeHolder:nil];
    
    if (!_mystr) {
        //
        return CGSizeMake(_boundSize.width, 20);
        
    }
    
    if ([_mystr isEqual: [NSNull null]] || _mystr == nil || [_mystr isEqualToString: @""] || [_mystr isEqualToString: @"<null>"])
    {
        return CGSizeMake(_boundSize.width, 20);
    }
    
    NSDictionary *attribute = @{NSFontAttributeName: font};
    CGSize size = [_mystr  boundingRectWithSize:_boundSize options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return size;
}
//
//计算字符串size
+ (CGSize)fc_getStringSizeWith:(NSString*)_mystr boundingRectWithSize:(CGSize)_boundSize font:(UIFont*)font{
    
    _mystr = [self tool_object:_mystr placeHolder:nil];
    
    if (!_mystr) {
        //
        return CGSizeMake(_boundSize.width, 20);
        
    }
    
    //    if ([_mystr isEqual: [NSNull null]] || _mystr == nil || [_mystr isEqualToString: @""] || [_mystr isEqualToString: @"<null>"])
    //    {
    //        return CGSizeMake(_boundSize.width, 20);
    //    }
    
    NSDictionary *attribute = @{NSFontAttributeName: font};
    CGSize size = [_mystr  boundingRectWithSize:_boundSize options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return size;
}
//
+(NSArray *)tool_getWelcomPics{
    NSDictionary* dmdic = [self tool_getPlistDict];
    NSArray* pics = dmdic[@"Welcome pictures"];
    if (!pics || pics.count == 0) {
//        return @[kNotFoundObj(@"")];
        return @[];
    }
    return pics;
}

// plist
+(NSDictionary *)tool_getPlistDict{
//    NSString* path = [kBundle pathForResource:@"QTInfo" ofType:@"plist"];
//    return [NSDictionary dictionaryWithContentsOfFile:path];
    return [NSDictionary new];
}
//
+(NSMutableAttributedString *)tool_addMiddleLineWithLabel:(UILabel *)lb withStr:(NSString *)str{
    NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:str attributes:attribtDic];
   [attribtStr addAttributes:@{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),NSBaselineOffsetAttributeName:@(0)} range:NSMakeRange(0, attribtStr.length)];
    lb.attributedText = attribtStr;
    return attribtStr;
}
//
+(void)tool_addDownLineWithLabel:(UILabel *)lb withStr:(NSString *)str{
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:str attributes:attribtDic];
    lb.attributedText = attribtStr;
}
+(UIView *)tool_returnLine{
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = RGBAColor(235, 235, 235,1);
    return line;
}

/**
 * 指定一个活动指示器
 */
+ (void)tool_showIndicatorOnView:(UIView*)supview withRect:(CGRect)rect{
    //
    [self tool_stopIndicatorOnView:supview];
    UIActivityIndicatorView* activityView = [[UIActivityIndicatorView alloc] initWithFrame:rect];
    activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    activityView.tag =  99;
    [supview addSubview:activityView];
    [activityView startAnimating];
}
/**
 * 取消一个活动指示器
 */
+ (void)tool_stopIndicatorOnView:(UIView*)supview{
    //
    UIActivityIndicatorView* activityView = (UIActivityIndicatorView*)[supview viewWithTag:99];
    
    [activityView stopAnimating];
    [activityView removeFromSuperview];
}

void ShowSuccessStatus(NSString *statues){
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showSuccessWithStatus:statues];
        });
    }else{
        [SVProgressHUD showSuccessWithStatus:statues];
    }
}

void ShowMessage(NSString *statues){
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:statues];
        });
    }else{
        [SVProgressHUD showInfoWithStatus:statues];
    }
}

void ShowErrorStatus(NSString *statues){
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:statues];
//            [SVProgressHUD showProgress:0.5 status:@"上传" maskType:SVProgressHUDMaskTypeGradient];
            [SVProgressHUD showProgress:0.5 status:@"上传"];
        });
    }else{
        [SVProgressHUD showErrorWithStatus:statues];
    }
}

void ShowMaskStatus(NSString *statues){
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            [SVProgressHUD showWithStatus:statues maskType:SVProgressHUDMaskTypeGradient];
            [SVProgressHUD showWithStatus:statues];
        });
    }else{
//        [SVProgressHUD showWithStatus:statues maskType:SVProgressHUDMaskTypeGradient];
        [SVProgressHUD showWithStatus:statues];
    }
}
void ShowProgress(CGFloat progress){
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            [SVProgressHUD showProgress:progress maskType:SVProgressHUDMaskTypeGradient];
            [SVProgressHUD showProgress:progress];
        });
    }else{
//        [SVProgressHUD showProgress:progress maskType:SVProgressHUDMaskTypeGradient];
        [SVProgressHUD showProgress:progress];
    }
}
void DismissHud(void){
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }else{
        [SVProgressHUD dismiss];
    }
}
+ (void)tool_saveAppKeyWithkey:(NSString *)strKey{
    //1499302797574074
//    [kQTUserDefaults setObject:strKey forKey:kAppKey];
    
}

+ (NSString *)tool_getAppKey{
//    return [kQTUserDefaults objectForKey:kAppKey];
    return @"";
}
#pragma mark --计算字符串size
+ (CGSize)getStringSizeWith:(NSString*)_mystr boundingRectWithSize:(CGSize)_boundSize font:(UIFont*)font{
    
    if ([_mystr isEqual: [NSNull null]] || _mystr == nil || [_mystr isEqualToString: @""] || [_mystr isEqualToString: @"<null>"])
    {
        return CGSizeMake(_boundSize.width, 0);
    }
    
    NSDictionary *attribute = @{NSFontAttributeName: font};
    CGSize size = [_mystr  boundingRectWithSize:_boundSize options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return size;
}

+(CGFloat)tool_floderSize{
    CGFloat folderSize = 0.0;
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
    
    //获取所有文件的数组
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    NSLog(@"文件数：%ld",files.count);
    
    for(NSString *path in files) {
        
        NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
        //累加
        folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1024.0/1024.0;
    
    return sizeM;
}
+(void)tool_removeFloderWithBlock:(void(^)(BOOL))returnSuccess{
    //===============清除缓存==============
    //获取路径
    NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    
    //返回路径中的文件数组
    NSArray*files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError*error;
        
        NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:path])
        {
            BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            if(isRemove) {
                NSLog(@"清除成功");
                returnSuccess(YES);
            }else{
                returnSuccess(NO);
                NSLog(@"清除失败");
            } 
        }
    }
}

/**
 * 换算时间:几秒前、几分钟前、、、、、、
 * 参数：时间戳
 */
+(NSString *)tool_mergeTimeWithTimeString:(NSString *)string{
    // 获取当前时时间戳 1466386762.345715 十位整数 6位小数
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    // 创建歌曲时间戳(后台返回的时间 一般是13位数字)
    NSTimeInterval createTime = [string longLongValue]/1000;
    // 时间差
    NSTimeInterval time = currentTime - createTime;
    
    NSInteger sec = time/60;
    if (sec<60) {
        return [NSString stringWithFormat:@"%ld分钟前",sec];
    }
    
    // 秒转小时
    NSInteger hours = time/3600;
    if (hours<24) {
        return [NSString stringWithFormat:@"%ld小时前",hours];
    }
    //秒转天数
    NSInteger days = time/3600/24;
    if (days < 30) {
        return [NSString stringWithFormat:@"%ld天前",days];
    }
    //秒转月
    NSInteger months = time/3600/24/30;
    if (months < 12) {
        return [NSString stringWithFormat:@"%ld月前",months];
    }
    //秒转年
    NSInteger years = time/3600/24/30/12;
    return [NSString stringWithFormat:@"%ld年前",years];
}

+(NSString *)tool_mergeTimeWithFormatTimeString:(NSString *)string{
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSDate *timeDate = [dateFormatter dateFromString:string];
    
    //得到与当前时间差
    NSTimeInterval  timeInterval = [timeDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    //标准时间和北京时间差8个小时
    timeInterval = timeInterval - 8*60*60;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    
    else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    
    else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }
    else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    
    return  result;
}

/**
 * 获取存储文件路径
 */
+(NSString *)tool_getFilePath:(NSString *)plistName{
    // 找到Documents文件所在的路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [paths objectAtIndex:0];
    // 把文件加入
    NSString *plistPath = [filePath stringByAppendingPathComponent:plistName];
    return plistPath;
}
/**
 * 把字符串替换成星号:手机号*替换
 */

+(NSString *)replaceStringWithAsterisk:(NSString *)originalStr startLocation:(NSInteger)startLocation lenght:(NSInteger)lenght

{
    
    NSString *newStr = originalStr;
    
    for (int i = 0; i < lenght; i++) {
        
        NSRange range = NSMakeRange(startLocation, 1);
        
        newStr = [newStr stringByReplacingCharactersInRange:range withString:@"*"];
        
        startLocation ++;
        
    }
    
    return newStr;
}
/**
 *label展示不同字体颜色
 */
+(NSMutableAttributedString *)getStrWithAllStr:(NSString *)allStr rangeStr:(NSString *)rangeStr color:(UIColor *)color font:(CGFloat)font{
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:allStr];
    NSRange range1 = [[str string] rangeOfString:rangeStr];
    [str addAttribute:NSForegroundColorAttributeName value:themeColor range:range1];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:range1];
    return str;
}
/**
 *获取当前时间戳
 */
+ (NSString *)getNowTime{
    // 获取时间（非本地时区，需转换）
    NSDate * today = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:today];
    // 转换成当地时间
    NSDate *localeDate = [today dateByAddingTimeInterval:interval];
    // 时间转换成时间戳
    NSTimeInterval timeSp = [localeDate timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeSpStr = [NSString stringWithFormat:@"%.0f",timeSp];//@"1517468580"
    return timeSpStr;
}
/**
 *获取签名
 */
+(NSString *)getAuthorizationWithToken:(NSString *)token api:(NSString *)api device:(NSString *)device timestamp:(NSString *)timestamp version:(NSString *)version{
    //    signature = hmac-sha1(api, device + "\n" + timestamp + "\n" + version)
    
    //    NSString *keyStr = @"/auth/rider/login";
    //    NSString *valueStr = @"ios\n1540525890205\n1.0.0";
    //    NSString *signature = [HMAC_SHA1 hmacSha1:keyStr value:valueStr];
    //    NSLog(@"signature = %@",signature);
    //    NSString *token = @"8fa3878feeb94ce491056130235e44d2";
    //    NSString *str =[NSString stringWithFormat:@"%@:%@",token,signature];
    //    NSString *Authorization = [Base64 base64EncodeString:str];
    //    NSLog(@"Base64 str = %@",Authorization);
    
    NSString *valueStr = [NSString stringWithFormat:@"%@\n%@\n%@",device,timestamp,version];
    NSString *signature = [Encipherment hmacSha1:api value:valueStr];
    NSString *str =[NSString stringWithFormat:@"%@:%@",token,signature];
    NSString *authorization = [Encipherment base64EncodeString:str];
    return authorization;
    
    
}

/**
 *字典转json字符串方法
 */
+(NSString *)convertToJsonData:(NSDictionary *)dict

{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
/**
 *JSON字符串转化为字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
/**
 *error
 */
+ (NSString *)analyticalHttpErrorDescription:(NSError *)error
{
    __weak NSDictionary *userInfo = error.userInfo;
    if (userInfo.count > 0) {
        return [QTTools stringForValue:[userInfo objectForKey:@"NSLocalizedDescription"]];
    }
    return error.description;
}

+ (id)stringForValue:(id)obj
{
    if (obj == nil||
        obj == NULL||
        [obj isKindOfClass:[NSNull class]]) {
        return @"";
    }
    else if ([obj isKindOfClass:[NSString class]])
    {
        return obj;
    }
    else if ([obj isKindOfClass:[NSNumber class]])
    {
        return obj;
    }
    
    return @"";
}
@end
